package cn.codeforfun.client;

import cn.codeforfun.generator.model.Client;
import cn.codeforfun.utils.JsonUtils;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.springframework.beans.BeanUtils;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author wangbin
 */
@EqualsAndHashCode(callSuper = true)
@Data
public class ClientVO extends Client implements ClientDetails {
    private static final long serialVersionUID = 8651872695105702271L;

    public static ClientVO from(Client client) {
        ClientVO result = new ClientVO();
        BeanUtils.copyProperties(client, result);
        return result;
    }

    @Override
    public Integer getAccessTokenValiditySeconds() {
        return super.getClientAccessTokenValiditySeconds();
    }

    @Override
    public Integer getRefreshTokenValiditySeconds() {
        return super.getClientRefreshTokenValiditySeconds();
    }

    @Override
    public Set<String> getResourceIds() {
        return StringUtils.commaDelimitedListToSet(super.getClientResourceIds());
    }

    @Override
    public boolean isSecretRequired() {
        return ObjectUtils.isEmpty(super.getClientSecret());
    }

    @Override
    public boolean isScoped() {
        return this.getScope().size() > 0;
    }

    @Override
    public Set<String> getScope() {
        return StringUtils.commaDelimitedListToSet(super.getClientScope());
    }

    @Override
    public Set<String> getAuthorizedGrantTypes() {
        return StringUtils.commaDelimitedListToSet(super.getClientAuthorizedGrantTypes());
    }

    @Override
    public Set<String> getRegisteredRedirectUri() {
        return StringUtils.commaDelimitedListToSet(super.getClientRegisteredRedirectUri());
    }

    @Override
    public Collection<GrantedAuthority> getAuthorities() {
        return StringUtils.commaDelimitedListToSet(super.getClientAuthorities()).stream()
                .map(a -> (GrantedAuthority) () -> a).collect(Collectors.toSet());
    }

    @Override
    public boolean isAutoApprove(String scope) {
        if (ObjectUtils.isEmpty(super.getClientAutoApproveScope())) {
            return false;
        }
        return super.getClientAutoApproveScope().contains(scope);
    }

    @Override
    public Map<String, Object> getAdditionalInformation() {
        if (super.getClientAdditionalInformation() == null) {
            return new HashMap<>(0);
        }
        return JsonUtils.toMap(super.getClientAdditionalInformation());
    }
}
